package controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import model.Model;
import model.UserDAO;

import org.mybeans.dao.DAOException;
import org.mybeans.form.FormBeanException;
import org.mybeans.form.FormBeanFactory;

import beans.User;

import formbeans.RegisterForm;
/*
 *  Course: S09-15437 - WEB APPLICATION DEVELOPMENT 
 * 	Name: Jiale Huang
 * 	Andrew ID: jialeh
 * 	Date: 2/23/2009
 *  Assignment: Hw4
 */

public class RegisterAction extends Action {

	private FormBeanFactory<RegisterForm> formBeanFactory = FormBeanFactory.getInstance(RegisterForm.class);
	
	private UserDAO userDAO;
	
	public RegisterAction(Model model){
		
		userDAO = model.getUserDAO();
	}
	
	@Override
	public String getName() {
		return "register.do";
	}

	@Override
	public String perform(HttpServletRequest request) {
		
		List<String> errors = new ArrayList<String>();
		request.setAttribute("errors", errors);
		
		try{
			RegisterForm form = formBeanFactory.create(request);
	        request.setAttribute("form",form);
			
	        // If no params were passed, return with no errors so that the form will be
	        // presented (we assume for the first time).
	        if (!form.isPresent()) {
	            return "register.jsp";
	        }
	
	        // Any validation errors?
	        errors.addAll(form.getValidationErrors());
	        if (errors.size() != 0) {
	            return "register.jsp";
	        }
	        
	        // Create the user bean
	        User user = userDAO.create(form.getUserEmail());
	        user.setFName(form.getFName());
	        user.setLName(form.getLName());
	        user.setPassWord(form.getPassword());
        	userDAO.update(user);
        
			// Attach (this copy of) the user bean to the session
	        HttpSession session = request.getSession(false);
	        session.setAttribute("user",user);
	
	        // After successful registration (and login) send to...
	        String redirectTo = (String) session.getAttribute("redirectTo");
	        if (redirectTo != null) return redirectTo;
	        
	        // If redirectTo is null, redirect to the "manage" action
			String webapp = request.getContextPath();
			return webapp + "/manage.do";
	        
			
		}catch(DAOException e){
        	errors.add(e.getMessage());
        	return "register.jsp";
		}catch(FormBeanException e){
        	errors.add(e.getMessage());
        	return "register.jsp";			
		}
	}

}
